package com.niuniu.rushdorm.filter;

/**
 * @author Meng
 */

import com.niuniu.rushdorm.exception.ReportedException;
import com.niuniu.rushdorm.pojo.entity.Log;
import com.niuniu.rushdorm.pojo.vo.ResultVO;
import com.niuniu.rushdorm.service.LogService;
import com.niuniu.rushdorm.util.JsonUtils;
import com.niuniu.rushdorm.util.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于捕获全局异常返回相应信息
 */
@Slf4j
@Component
public class ExceptionHandlerFilter extends OncePerRequestFilter {


    @Autowired
    LogService logService;
    @Override
    protected void initFilterBean() throws ServletException {
        super.initFilterBean();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        log.debug("exception filter");
        //默认将操作日志记录到数据库
        httpServletRequest.setAttribute("log_flag",true);
        try{
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            httpServletRequest.setAttribute("log_status", Log.SUCCESS);
            httpServletRequest.setAttribute("code",200);
            httpServletRequest.setAttribute("msg","成功");
        }catch (Exception e){
            Throwable cause = e;
            while(cause.getCause()!=null){
                cause = cause.getCause();
            }
            ResultVO resultVO;
            httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
            httpServletResponse.setCharacterEncoding("utf-8");
            if(cause instanceof ReportedException){
                resultVO = ResultVO.fail((ReportedException) cause);
            }else{
                resultVO = ResultVO.fail(ReportedException.build(StatusEnum.UNCODE_ERROR));
                System.out.println(cause.getMessage());
                cause.printStackTrace();
            }
            httpServletResponse.getWriter().write(JsonUtils.toJsonString(resultVO));
            httpServletRequest.setAttribute("log_status",Log.FAIL);
            httpServletRequest.setAttribute("code",resultVO.getCode());
            httpServletRequest.setAttribute("msg",resultVO.getMessage());
        }
        finally {
            Boolean log_flag = (Boolean)httpServletRequest.getAttribute("log_flag");
            if(!httpServletRequest.getMethod().equals("GET") && log_flag!=null && log_flag.equals(true)){
                logService.logToDB(httpServletRequest,httpServletResponse);
            }
        }
    }
}
